# coding=utf-8
import os
import re
from tkinter import *
from tkinter import filedialog
from tkinter import font
from tkinter import messagebox
from tkinter.ttk import Combobox
from MergeExcel.core import multiple_excel_merge_multiple_sheet, multiple_excel_merge_single_sheet
from utils.file import get_file_list,write_config,read_config


class MyGUI:
    def __init__(self, window):
        """
        初始化窗口
        :param window:
        """
        self.window = window
        # 初始化数据
        self.merge_types = ["将多个excel合并到同一excel下的多张工作表",
                            "将多个excel合并到同一excel下的同一工作表"]
        self.sort_keys = ["文件名称", "修改日期", "文件大小", "文件数字"]
        self.sort_modes = ["升序", "降序"]
        # 尝试读取配置文件
        init_config = {
            "merge_type": self.merge_types[0],
            "folder": "",
            "start_row": 2,
            "sort_key": self.sort_keys[1],
            "sort_mode": self.sort_modes[0],
        }
        init_config.update(read_config())   # 合并配置文件
        # 初始化控件变量
        self.merge_type_var = StringVar(value=init_config["merge_type"])    # 合并类型
        self.folder_var = StringVar(value=init_config["folder"])  # 文件夹路径
        self.start_row_var = IntVar(value=int(init_config["start_row"]))  # 合并起始行
        self.sort_key_var = StringVar(value=init_config["sort_key"])  # 排序项
        self.sort_mode_var = StringVar(value=init_config["sort_mode"])  # 排序方式
        # 初始化控件
        self.start_row_spinbox = None
        self.enter_button = None  # 确定按钮
        self.progress_label = None  # 显示过程标签

    def set_window_style(self):
        """
        设置窗口样式
        :return:
        """
        screen_width = self.window.winfo_screenwidth()
        screen_height = self.window.winfo_screenheight()
        width, height = 400, 240
        x = int(screen_width / 2 - width / 2)
        y = int(screen_height / 2 - height / 2)
        size = '{}x{}+{}+{}'.format(width, height, x, y)  # 设置宽高和居中显示
        self.window.geometry(size)
        self.window.title("合并Excel-王凤龙")

    def set_window_menu(self):
        """
        设置菜单
        :return:
        """
        menu_bar = Menu(self.window)
        menu_bar.add_command(label="联系我", command=lambda: messagebox.showinfo("联系我", "微信号：i-aisx"))
        menu_bar.add_command(label="保存配置", command=lambda: self.save_config())
        menu_bar.add_command(label="关闭", command=lambda: self.window.destroy())
        self.window.config(menu=menu_bar)

    def set_window_layout(self):
        """
        设置窗口布局
        :return:
        """
        """选择合并类型"""
        merge_type_frame = Frame(self.window)
        Label(merge_type_frame, text='合并的类型：').pack(side=LEFT, padx=5)
        merge_type_combobox = Combobox(merge_type_frame, values=self.merge_types, textvariable=self.merge_type_var)
        merge_type_combobox.bind("<<ComboboxSelected>>", self.merge_type_handle)
        merge_type_combobox.pack(side=LEFT, padx=5, fill=X, expand=True)
        merge_type_frame.pack(pady=5, fill=X)
        """选择目录"""
        folder_frame = Frame(self.window)  # 创建文件夹选择框架
        Label(folder_frame, text='文件夹路径：') \
            .pack(side=LEFT, padx=5)  # 控件在框架内自左向右排列（排列方式）
        Entry(folder_frame, textvariable=self.folder_var) \
            .pack(side=LEFT, padx=5, fill=X, expand=True)  # 自动填充X轴方向剩余宽度
        Button(folder_frame, text='选择目录', cursor="hand2", command=self.open_folder) \
            .pack(side=LEFT, padx=5)
        folder_frame.pack(pady=5, fill=X)  # 框架靠左显示，并占满X轴（对齐方式）
        """合并起始行"""
        start_row_frame = Frame(self.window)
        Label(start_row_frame, text='从第').pack(side=LEFT, padx=5)
        self.start_row_spinbox = Spinbox(start_row_frame, width=5, justify=CENTER, state=DISABLED,
                                         from_=0, to=10, increment=1, textvariable=self.start_row_var)
        self.start_row_spinbox.pack(side=LEFT, padx=5)
        Label(start_row_frame, text='行开始合并').pack(side=LEFT, padx=5)
        start_row_frame.pack(pady=5, fill=X)
        """排序项和排序方式"""
        sort_frame = Frame(self.window)
        Label(sort_frame, text='按照').pack(side=LEFT, padx=5)
        sort_key_combobox = Combobox(sort_frame, values=self.sort_keys, width=10,textvariable=self.sort_key_var)
        sort_key_combobox.bind("<<ComboboxSelected>>", self.update_file)
        sort_key_combobox.pack(side=LEFT, padx=5)
        sort_mode_combobox = Combobox(sort_frame, values=self.sort_modes, width=5,textvariable=self.sort_mode_var)
        sort_mode_combobox.bind("<<ComboboxSelected>>", self.update_file)
        sort_mode_combobox.pack(side=LEFT, padx=5)
        Label(sort_frame, text='读取文件').pack(side=LEFT, padx=5)
        sort_frame.pack(pady=5, fill=X)
        """确定"""
        self.enter_button = Button(self.window, text='确定', cursor="hand2", width=8, command=self.enter_handle,
                                   font=font.Font(size=16, weight="bold"))
        self.enter_button.pack(pady=20)
        """读取过程"""
        self.progress_label = Label(self.window, text='总进度(0/0)')
        self.progress_label.pack(side=LEFT, padx=5)

    def open_folder(self):
        """
        打开文件夹
        :return:
        """
        folder = filedialog.askdirectory()
        if len(folder) > 0:
            self.folder_var.set(folder)
            self.update_file()

    def merge_type_handle(self, event=None):
        """
            合并类型处理
        """
        merge_type = self.merge_type_var.get()
        if merge_type == self.merge_types[0]:
            self.start_row_spinbox["state"] = DISABLED
        if merge_type == self.merge_types[1]:
            self.start_row_spinbox["state"] = NORMAL

    def update_file(self, event=None):
        """
        更新文件
        :return:
        """
        folder = self.folder_var.get()
        if len(folder.strip()) > 0:
            files = get_file_list(folder,
                                  ".xlsx",
                                  self.sort_key_var.get(),
                                  self.sort_mode_var.get())
            if len(files) > 0:
                self.progress_label["text"] = "总进度({}/{}): {}".format(0, len(files), os.path.basename(files[0]))
            else:
                self.progress_label["text"] = "总进度(0/0)"

    def enter_handle(self):
        """
        确定处理
        :return:
        """
        """获取用户输入的各个值"""
        merge_type = self.merge_type_var.get()
        folder = self.folder_var.get()
        start_row = self.start_row_var.get()
        sort_key = self.sort_key_var.get()
        sort_mode = self.sort_mode_var.get()
        """检验文件夹路径"""
        if len(folder.strip()) == 0:
            messagebox.showwarning("提示", "文件夹路径不能为空")
            return
        """选择文件保存路径"""
        # 返回选择文件的文件名字，但不具备保存文件的能力
        file_name = filedialog.asksaveasfilename(initialfile="合并汇总.xlsx",  # 默认文件名称
                                                 filetypes=[("XLSX", "*.xlsx")])
        if len(file_name) == 0:
            return
        """判断文件是否打开"""
        if os.path.exists(file_name):
            try:
                file = open(file_name, "a")  # 以追加方式打开
                file.close()
            except PermissionError:
                messagebox.showwarning("提示", "请先关闭已打开的{}".format(file_name))
                return
        """根据文件类型调用合并函数"""
        self.enter_button["state"] = DISABLED
        if merge_type == self.merge_types[0]:
            result_file = multiple_excel_merge_multiple_sheet(folder, sort_key, sort_mode, self.progress_show)
        else:
            result_file = multiple_excel_merge_single_sheet(folder, start_row, sort_key, sort_mode, self.progress_show)
        result_file.save(file_name)
        messagebox.showinfo("提示", "合并完成")
        self.enter_button["state"] = NORMAL

    def progress_show(self, index, length, text):
        """
        显示处理进度
        :param index: 当前读取位置
        :param length: 总长度
        :param text: 当前读取的文件名称
        :return:
        """
        self.progress_label["text"] = "总进度({}/{}): {}".format(index + 1, length, text)

    def save_config(self):
        """
        保存配置
        :return:
        """
        write_config(configs={
            "merge_type":self.merge_type_var.get(),
            "folder":self.folder_var.get(),
            "start_row":self.start_row_var.get(),
            "sort_key":self.sort_key_var.get(),
            "sort_mode":self.sort_mode_var.get(),
        })
        messagebox.showinfo("提示", "当前配置已保存")



def start():
    """
    启动gui
    :return:
    """
    window = Tk()
    gui = MyGUI(window)
    gui.set_window_style()
    gui.set_window_menu()
    gui.set_window_layout()
    window.mainloop()


if __name__ == "__main__":
    start()
